const express = require('express');
const router = express.Router();
const crypto = require('crypto');
const sys_user = require('../../../models/sys_user');

router.post('/sys/user/login', async (req, res) => {
    try {
        const { username, password } = req.body

        // 获取用户IP地址
        //console.log('req.headers:', req.headers);
        const userIp = req.ip || req.socket.remoteAddress;
        console.log(`最终获取的用户IP: ${userIp}`);

        //获取用户盐值
        const salt = await sys_user.getSalt(username)

        //使用md5算法加密后的密码查询sys_user表的用户密码是否匹配
        const md5 = crypto.createHash('md5');
        const encryptedPwd = md5.update(password + salt).digest('hex')

        //使用JWT加密
        const jwt = require('jsonwebtoken')
        const token = jwt.sign({ username: username }, 'secret-key', { expiresIn: '1h' })

        // 查询用户
        const user = await sys_user.findUserByUsernameAndPassword(username, encryptedPwd)
        if (!user) {
            return res.json({
                msg: "用户名或密码错误",
                code: 90010002,
                success: false,
                username: username,
                salt: salt,
                password: encryptedPwd
            })
        }

        if (user.data_flag == 1) {
            return res.json({
                "msg": "您的账号已被禁用！请联系管理员处理",
                "code": 90010003,
                "success": false
            })
        }

        //登录成功更新用户在线状态
        await sys_user.updateUserState(user.id, 1)

        return res.json({
            "msg": "操作成功！",
            "code": 0,
            "data": {
                "id": user.id,
                "userName": user.user_name,
                "realName": user.real_name,
                "roleIds": user.role_ids,
                "departId": user.depart_id,
                "createTime": user.create_time,
                "updateTime": user.update_time,
                "state": user.state,
                "roles": user.role_ids,
                "token": token
            },
            "success": true
        })
    } catch (error) {
        console.error("数据库查询失败:", error)
        return res.status(500).json({
            msg: "数据库查询失败",
            code: 500,
            success: false
        })
    }
})

router.post('/sys/user/info', async (req, res) => {
    try {
        const { token } = req.headers  // 从请求体中获取token

        if (!token) {
            return res.status(401).json({
                msg: "未提供token",
                code: 401,
                success: false
            })
        }

        // 验证JWT token
        const jwt = require('jsonwebtoken')
        let decoded;
        try {
            decoded = jwt.verify(token, 'secret-key')
        } catch (error) {
            console.error("JWT验证失败:", error)
            return res.status(401).json({
                msg: "token无效或已过期",
                code: 401,
                success: false
            })
        }

        // 根据token中的用户名查询用户信息
        const user = await sys_user.findUserByUsername(decoded.username)
        if (!user) {
            return res.status(404).json({
                msg: "用户不存在",
                code: 404,
                success: false
            })
        }

        return res.json({
            "msg": "操作成功！",
            "code": 0,
            "data": {
                "id": user.id,
                "userName": user.user_name,
                "realName": user.real_name,
                "roleIds": user.role_ids,
                "departId": user.depart_id,
                "createTime": user.create_time,
                "updateTime": user.update_time,
                "state": user.state,
                "roles": user.role_ids ? user.role_ids.split(',') : [],
                "token": token  // 返回相同的token
            },
            "success": true
        })
    } catch (error) {
        console.error('获取用户信息错误:', error);
        return res.status(500).json({
            msg: "服务器内部错误",
            code: 500,
            success: false
        })
    }
})



router.post('/sys/user/logout', async (req, res) => {
    try {
        const { token } = req.body

        if (!token) {
            // 如果没有token，直接返回成功但不更新状态
            return res.json({
                "msg": "登出成功！",
                "code": 0,
                "success": true
            })
        }

        // 验证JWT token并获取用户信息
        const jwt = require('jsonwebtoken')
        let decoded;
        try {
            decoded = jwt.verify(token, 'secret-key')
        } catch (error) {
            // token无效或过期，直接返回成功但不更新状态
            console.error("JWT验证失败:", error)
            return res.json({
                "msg": "登出成功！",
                "code": 0,
                "success": true
            })
        }

        // 根据token中的用户名查询用户信息
        const user = await sys_user.findUserByUsername(decoded.username)
        if (user) {
            // 登出更改用户在线状态为0
            await sys_user.updateUserState(user.id, 0)
            console.log(`用户 ${user.user_name} 已登出，状态更新为离线`)
        }

        return res.json({
            "msg": "请求成功！",
            "code": 0,
            "success": true,
        })
    } catch (error) {
        console.error("数据库查询失败:", error)
        return res.status(500).json({
            msg: "服务器内部错误",
            code: 500,
            success: false
        })
    }
})

module.exports = router;